package com.loopy.tomcat;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class TomcatV01 {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(8080);
        System.out.println("========mytomcat在8080端口监听======");

        while (!serverSocket.isClosed()) {
            Socket socket = serverSocket.accept();
            InputStream inputStream = socket.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
            String msg = null;
            System.out.println("=======接收到浏览器发送的数据======");
            while ((msg = br.readLine()) != null) {
                //读到空的字符串退出
                if (msg.length() == 0) {
                    break;
                }
                System.out.println(msg);
            }
            /*
            HTTP/1.1 200 OK
            Server: Apache-Coyote/1.1
            Content-Type: text/html;charset=utf-8
            Transfer-Encoding: chunked
            Date: Tue, 16 Jan 2024 02:19:32 GMT
            * 模仿写出响应头*/
            OutputStream outputStream = socket.getOutputStream();
            String resHeader="HTTP/1.1 200 OK\r\n" +
                    "Content-Type: text/html;charset=utf-8\r\n\r\n" ;
            String res=resHeader+"hi loopy欢迎来中国";
            System.out.println("=========我们给浏览器发送的数据==========");
            System.out.println(res);
            outputStream.write(res.getBytes());
            outputStream.flush();
            outputStream.close();
            inputStream.close();
            br.close();
            socket.close();


        }
    }
}
